package com.aletto.general_store.utils;

import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 控制小数点位数
 */
public class DecimalDigitsInputFilter implements TextWatcher {

    private final int decimalPlaces;

    public DecimalDigitsInputFilter(int decimalPlaces) {
        this.decimalPlaces = decimalPlaces;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.toString().contains(".")) {
            int index = s.toString().indexOf(".");
            int decimalCount = s.toString().length() - index - 1;
            if (decimalCount > decimalPlaces) {
                s.delete(index + decimalPlaces + 1, s.length());
            }
        }
    }

}
